<?php

namespace App\Http\Controllers\Mobile\Company;

use App\Http\Requests\Company\Login\AjaxCompanyLoginRequest;
use App\Models\Company\CompanyLoginRecord;
use App\Models\Company\CompanyTrialError;
use App\Models\Company\CompanyVisitRecord;
use Auth;

class LoginController extends CommonController{
    /**
     * ajax验证登录
     * @param AjaxCompanyLoginRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function ajaxCompanyLogin(AjaxCompanyLoginRequest $request){
        $input = $request->only('username', 'password', 'remember');
        //用户和手机登录多可以
        $remember = !empty($input['remember']) ? $input['remember'] : false;
        if(Auth::guard('company')->attempt(['username' => $input['username'], 'password' => $input['password']], $remember)){
            $user = auth()->guard('company')->user();
            //登录记录表
            $this->loginRecord($user);
            return response()->json(['status' => '0', 'msg' => '登录用户成功!']);
        }else if(Auth::guard('company')->attempt(['mobile' => $input['username'], 'password' => $input['password']], $remember)){
            $user = auth()->guard('company')->user();
            //登录记录表
            $this->loginRecord($user);
            return response()->json(['status' => '0', 'msg' => '登录用户成功!']);
        }else{
            //企业试错登录记录
            $this->trialErrorRecord($input);
            return response()->json(['status' => '1', 'msg' => '用户名或者密码错误!']);
        }
    }
    /**
     * 企业试错记录信息表
     * @param $userInfo
     */
    public function trialErrorRecord($input){
        //试错记录表
        $trial = array();
        $trial['username'] = $input['username'];
        $trial['password'] = $input['password'];
        $trial['company_login_ip'] = getIp();
        //登录记录表
        CompanyTrialError::create($trial);
    }

    /**
     * 登录记录信息
     * @param $userInfo
     */
    public function loginRecord($user){
        //登录记录表
        $record = array();
        $record['uid'] = $user->uid;
        $record['company_login_ip'] = getIp();
        $record['company_login_time'] = date('Y-m-d H:i:s', time());
        $record['login_type'] = 4;
        $record['type'] = 1;
        //登录记录表
        CompanyLoginRecord::create($record);
        //更新用户表
        $currtime = date('Y-m-d H:i:s', time());
        $fifedate = date('Y-m-d H:i:s', strtotime($user->surpris_visit_time . "+15 day"));
        if($fifedate < $currtime){
            $user->surpris_visit_time = date('Y-m-d H:i:s', time());
            //15天内插入突访记录表
            CompanyVisitRecord::create($record);
        }
        $user->last_login_time = date('Y-m-d H:i:s', time());
        $user->last_login_ip = getIp();
        $user->save();
    }

}